﻿//-------------------------------------------------------------------
//文件名称：TPaper.cs
//模块名称：TPaper业务逻辑接口层
//功能说明：
//-----------------------------------------------------------------
//修改记录：
//修改人：Dawen
//-----------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using ELearning.Common.Extensions;
using ELearning.Common.Helpers;
using ELearning.DAL;
using ELearning.Models;
using ELearning.Models.ViewModel.YTJYAdmin.Package;
using ELearning.Models.ViewModel.YTJYAdmin.Paper;
using ELearning.Models.ViewModel.YTJYAdmin.Study;

namespace ELearning.BLL
{
    /// <summary>
    /// TPaper业务逻辑接口层
    /// </summary>
    public partial class TPaperService : BaseService<TPaper>
    {
        /// <summary>
        /// 获取套餐列表
        /// </summary>
        public TPaperViewModel GetModelList(TPaperRequest request)
        {
            var models = RepositoryFactory.TPaperRepository.GetModelList(request);
            var viewModel = new TPaperViewModel { TotalCount = models.FirstOrDefault()?.Total ?? 0 };
            foreach (var m in models)
            {
                var v = m.MapTo<TPaperItem, TPaperModel>();
                viewModel.Items.Add(v);
            }
            return viewModel;
        }

        /// <summary>
        /// 获取试卷相关或者不相关的列表
        /// </summary>
        public TPaperQuestionViewModel GetModelRelevantList(TPaperQuestionRequest request)
        {
            var models = RepositoryFactory.TPaperRepository.GetModelRelevantList(request);
            var viewModel = new TPaperQuestionViewModel { TotalCount = models.FirstOrDefault()?.TotalCount ?? 0 };
            foreach (var m in models)
            {
                var v = m.MapTo<TPaperQuestionItem, TPaperQuestionModel>();
                viewModel.Items.Add(v);
            }
            return viewModel;
        }

        /// <summary>
        /// 获取客户端的试卷列表
        /// </summary>
        public SitePaperViewModel GetSitePaperList(SitePaperRequest request, Guid userId)
        {
            var models = RepositoryFactory.TPaperRepository.GetSitePaperList(request, userId);
            var viewModel = new SitePaperViewModel { TotalCount = models.FirstOrDefault()?.TotalCount ?? 0 };
            foreach (var model in models)
            {
                var v = model.MapTo<SitePaperItem, SitePaperModel>();
                viewModel.Items.Add(v);
            }

            return viewModel;
        }

        /// <summary>
        /// 获取试卷详情
        /// </summary>
        public SitePaperDetailViewModel GetSitePaperDetail(SitePaperDetailRequest request, Guid userId)
        {
            var models = RepositoryFactory.TPaperRepository.GetSitePaperDetail(request.PaperId);
            var viewModel = new SitePaperDetailViewModel();
            if (models.Any())
            {
                var p = models.First();
                viewModel = new SitePaperDetailViewModel
                {
                    PaperId = request.PaperId,
                    Name = p.Name,
                    Description = p.Description,
                    TimeSpan = p.TimeSpan,
                    Type = p.Type,
                    TotalScore = p.TotalScore
                };

                var history = new TPaperTestHistory
                {
                    Id = Guid.NewGuid(),
                    CategoryId = p.CategoryId,
                    CreateTime = DateTime.Now,
                    CreateUserId = userId,
                    CourseId = request.CourseId,
                    ChapterId = request.ChapterId,
                    Description = p.Description,
                    DoneCount = 0,
                    EndTime = DateTime.Now,
                    TimeSpan = 0,
                    UpdateTime = DateTime.Now,
                    StartTime = DateTime.Now,
                    TotalCount = p.TotalCount,
                    Type = p.Type,
                    UserId = userId,
                    IsDelete = false,
                    OrgCode = p.OrgCode,
                    UpdateUserId = userId,
                    PaperId = request.PaperId,
                    Status = 1,
                    Sort = 0,
                    Name = p.Name,
                    PackageId = request.PackageId,
                    TypeCode = p.TypeCode,
                    PaperTotalScore = p.TotalScore,
                    TotalScore = 0,
                    ErrorCount = 0,
                    LastQuestionId = Guid.Empty,
                    PaperTimeSpan = p.TimeSpan,
                    RightCount = 0,
                    Year = p.Year
                };
                viewModel.PaperTestHistoryId = history.Id;

                RepositoryFactory.TPaperTestHistoryRepository.Add(history);

                foreach (var model in models)
                {
                    var qt = viewModel.Items.FirstOrDefault(i => i.QuestionTypeCode == model.QuestionTypeCode);
                    if (qt.IsNull())
                    {
                        qt = new SiteQuestionTypeModel
                        {
                            QuestionTypeCode = model.QuestionTypeCode,
                            QuestionTypeName = model.QuestionTypeName
                        };
                        viewModel.Items.Add(qt);
                    }

                    var q = qt.Items.FirstOrDefault(i => i.QuestionItemId == model.QuestionItemId);
                    if (q.IsNull())
                    {
                        q = new SiteQuestionModel
                        {
                            QuestionId = model.QuestionId,
                            QuestionItemId = model.QuestionItemId,
                            Analysis = model.Analysis,
                            Answer = model.Answer,
                            Grade = model.Grade,
                            MainName = model.MainName,
                            QuestionName = model.QuestionName
                        };

                        qt.Items.Add(q);
                    }

                    var o = q.Items.FirstOrDefault(x => x.OptionId == model.OptionId);
                    if (o.IsNull() && model.OptionId.HasValue)
                    {
                        o = new SiteQuestionOptionModel
                        {
                            OptionName = model.OptionName,
                            OptionId = model.OptionId ?? Guid.Empty,
                            IsRight = model.IsRight ?? false
                        };

                        q.Items.Add(o);
                    }
                }

                viewModel.Items = viewModel.Items.OrderBy(i => i.QuestionTypeCode).ToList();
            }

            return viewModel;
        }

        /// <summary>
        /// 交卷
        /// </summary>
        public SubmitPaperViewModel SubmitPaper(SubmitPaperRequest request, Guid userId)
        {
            var viewModel = new SubmitPaperViewModel();
            
            using (var scope = new TransactionScope())
            {
                var history = RepositoryFactory.TPaperTestHistoryRepository.Find(h => h.Id == request.PaperTestHistoryId);
                if (history.IsNotNull())
                {
                    if (history.Status == 2)
                    {
                        viewModel.PaperTestHistoryId = history.Id;
                        viewModel.TotalScore = history.TotalScore;
                        viewModel.PaperTotalScore = history.PaperTotalScore;
                        return viewModel;
                    }

                    history.TotalCount = request.Items.Count;
                    history.RightCount = request.Items.Count(t => t.Status == 1);
                    history.ErrorCount = request.Items.Count(t => t.Status == 2);
                    history.DoneCount = request.Items.Count(t => t.Status != 0);
                    history.LastQuestionId = request.LastQuestionId;
                    history.EndTime = DateTime.Now;
                    history.UpdateTime = DateTime.Now;
                    history.TimeSpan = (int)((history.EndTime - history.StartTime).TotalSeconds);
                    history.Status = 2;
                    history.UpdateUserId = userId;

                    history.UserId = userId;
                    RepositoryFactory.TPaperTestHistoryRepository.UpdateNoSaveChange(history);
                    var models = RepositoryFactory.TPaperRepository.GetSitePaperDetail(history.PaperId);
                    foreach (var questionItem in request.Items)
                    {
                        var tempQ = models.FirstOrDefault(i => i.QuestionItemId == questionItem.QuestionItemId) ?? new SitePaperDetailModel();
                        var q = new TPaperQuestionTestHistory
                        {
                            Id = Guid.NewGuid(),
                            PaperTestHistoryId = history.Id,
                            Analysis = tempQ.Analysis,
                            Answer = tempQ.Answer,
                            ChoosedOptionId = string.Empty,
                            CreateTime = DateTime.Now,
                            CreateUserId = userId,
                            Difficulty = tempQ.Difficulty,
                            Grade = tempQ.Grade,
                            IsDelete = false,
                            MainName = tempQ.MainName,
                            OrgCode = tempQ.OrgCode,
                            UpdateTime = DateTime.Now,
                            UpdateUserId = userId,
                            PaperId = history.PaperId,
                            RightAnswer = tempQ.RightAnswer,
                            Name = tempQ.QuestionName,
                            QuestionId = tempQ.QuestionId,
                            QuestionItemId = tempQ.QuestionItemId,
                            Status = questionItem.Status,
                            InputAnswer = questionItem.InputAnswer,
                            Sort = tempQ.Sort,
                            QuestionTypeCode = tempQ.QuestionTypeCode,
                            UserGrade = 0
                        };
                        if (questionItem.Status == 1) //题目正确得分
                        {
                            q.UserGrade = tempQ.Grade;
                            history.TotalScore += q.UserGrade;
                        }
                        if (questionItem.ChoosedIdList.Any())
                            q.ChoosedOptionId = $"/{string.Join("/", questionItem.ChoosedIdList)}/";
                        RepositoryFactory.TPaperQuestionTestHistoryRepository.AddNoSaveChange(q); //添加题目历史记录

                        //保存选项历史记录
                        var tempOs = models.Where(i => i.QuestionItemId == questionItem.QuestionItemId).ToList();
                        foreach (var tempO in tempOs)
                        {
                            if (tempO.OptionId.HasValue)
                            {
                                var optionItem = questionItem.ChoosedIdList.FirstOrDefault(i => i == tempO.OptionId);
                                var o = new TPaperOptionTestHistory
                                {
                                    Id = Guid.NewGuid(),
                                    CreateTime = DateTime.Now,
                                    CreateUserId = userId,
                                    IsDelete = false,
                                    IsRight = tempO.IsRight ?? false,
                                    IsChoosed = optionItem != Guid.Empty,
                                    Name = tempO.OptionName,
                                    OptionId = tempO.OptionId.Value,
                                    PaperId = request.PaperId,
                                    PaperTestHistoryId = history.Id,
                                    QuestionId = questionItem.QuestionId,
                                    QuestionItemId = questionItem.QuestionItemId,
                                    UpdateTime = DateTime.Now,
                                    UpdateUserId = userId,
                                    Sort = tempO.QoSort ?? 0,
                                    PaperQuestionTestHistoryId = q.Id
                                };

                                RepositoryFactory.TPaperOptionTestHistoryRepository.AddNoSaveChange(o);
                            }
                        }
                    }

                    RepositoryFactory.TPaperOptionTestHistoryRepository.SaveChange();

                    viewModel.PaperTestHistoryId = history.Id;
                    viewModel.TotalScore = history.TotalScore;
                    viewModel.PaperTotalScore = history.PaperTotalScore;
                }

                scope.Complete();
            }
            return viewModel;
        }

        /// <summary>
        /// 获取答题记录信息
        /// </summary>
        public DonePaperDetailViewModel GetDonePaperDetail(Guid paperHistoryId)
        {
            var models = RepositoryFactory.TPaperRepository.GetDonePaperDetail(paperHistoryId);
            var viewModel = new DonePaperDetailViewModel();
            if (models.Any())
            {
                var p = models.First();
                viewModel = new DonePaperDetailViewModel
                {
                    PaperId = p.Id,
                    Name = p.Name,
                    Description = p.Description,
                    TimeSpan = p.TimeSpan,
                    Type = p.Type,
                    TotalScore = p.TotalScore,
                    PaperTestHistoryId = paperHistoryId
                };

                foreach (var model in models)
                {
                    var qt = viewModel.Items.FirstOrDefault(i => i.QuestionTypeCode == model.QuestionTypeCode);
                    if (qt.IsNull())
                    {
                        qt = new DonePaperDetailQuestionTypeModel
                        {
                            QuestionTypeCode = model.QuestionTypeCode,
                            QuestionTypeName = model.QuestionTypeName
                        };
                        viewModel.Items.Add(qt);
                    }

                    var q = qt.Items.FirstOrDefault(i => i.QuestionItemId == model.QuestionItemId);
                    if (q.IsNull())
                    {
                        q = new DonePaperDetailQuestionModel
                        {
                            QuestionId = model.QuestionId,
                            QuestionItemId = model.QuestionItemId,
                            Analysis = model.Analysis,
                            Answer = model.Answer,
                            Grade = model.Grade,
                            MainName = model.MainName,
                            QuestionName = model.QuestionName,
                            InputAnswer = model.InputAnswer,
                            ChoosedOptionId = model.ChoosedOptionId.Split('/').Where(s => s.Length > 0).ToList(),
                            RightAnswer = model.RightAnswer.Split('/').Where(s => s.Length > 0).ToList(),
                            Status = model.QStatus,
                            UserGrade = model.UserGrade
                        };

                        qt.Items.Add(q);
                    }

                    var o = q.Items.FirstOrDefault(x => x.OptionId == model.OptionId);
                    if (o.IsNull() && model.OptionId.HasValue)
                    {
                        o = new DonePaperDetailQuestionOptionModel
                        {
                            OptionName = model.OptionName,
                            OptionId = model.OptionId.Value,
                            IsRight = model.IsRight ?? false,
                            IsChoosed = model.IsChoosed ?? false
                        };

                        q.Items.Add(o);
                    }
                }

                viewModel.Items = viewModel.Items.OrderBy(i => i.QuestionTypeCode).ToList();
            }

            return viewModel;
        }
    }
}


